package com.kieoo.user.utils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Base64;

public class Base64Utils {
    /**
     * @param base64Str      base64字符编码
     * @param targetFilePath 文件存在电脑中的哪个位置(比如传: "D://")
     */
    public static void base64ToFile(String base64Str, String targetFilePath) {
        // 解码Base64字符串
        byte[] imageBytes = Base64.getDecoder().decode(base64Str);
        // 创建字节数组输入流
        ByteArrayInputStream bis = new ByteArrayInputStream(imageBytes);
        // 读取图片
        BufferedImage image;
        try {
            image = ImageIO.read(bis);
            bis.close();
            ImageIO.write(image, "webp", new File(targetFilePath));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
